<template>
	
   <div>
	   <!--面包屑区域-->
	   <el-breadcrumb separator-class="el-icon-arrow-right">
	     <el-breadcrumb-item :to="{ path: '/adminHome/center' }">首页</el-breadcrumb-item>
	     <el-breadcrumb-item>员工信息管理</el-breadcrumb-item>
	     <el-breadcrumb-item>员工信息</el-breadcrumb-item>
	   </el-breadcrumb>
	   <!--卡片视图-->
	   <el-card >
		   <el-row :gutter="20">  
		   
		         <el-col :span="8">  
		           <el-input placeholder="输入员工名称搜索"  v-model="searchQuery" @change="handleChange">
					<el-button slot="append" icon="el-icon-circle-close" @click="clearSearchQuery"></el-button>
				   </el-input>
				 </el-col>
				 <el-col :span="4">
				   <el-button @click="list()">显示员工列表</el-button>
		         </el-col>  
		       </el-row> 
	   </el-card>
	   <!--表格-->
	     <el-table
	       :data="tableData.slice((pageIndex-1)*pageSize,pageIndex*pageSize)"
	       style="width: 100%"
	       max-height="500">

		   <el-table-column
			fixed
		     prop="employeeID"
		     label="员工编号"
		     width="150">
		   </el-table-column>

	       <el-table-column
	         prop="name"
	         label="员工姓名"
	         width="150">
	       </el-table-column>

		   <el-table-column
   		   prop="departmentID"
   		   label="部门"
   		   width="150">
   		   <template slot-scope="scope">
   		     {{ getDepartmentName(scope.row.departmentID) }}
   		   </template>
   		 </el-table-column>

			<el-table-column
   			  prop="positionID"
   			  label="职位"
   			  width="150">
   			  <template slot-scope="scope">
   			    {{ getPositionName(scope.row.positionID) }}
   			  </template>
   			</el-table-column>

	       <el-table-column
	         prop="phone"
	         label="手机号"
	         width="180">
	       </el-table-column>

	       <el-table-column
	         prop="email"
	         label="邮箱"
	         width="180">
	       </el-table-column>

		   <el-table-column
	         prop="birthdate"
	         label="入职日期"
	         width="180">
	       </el-table-column>

	       <el-table-column
	         fixed="right"
	         label="操作"
	         width="120">
	         <template slot-scope="scope">
	           <el-button
	             @click="openDialog(scope.row)"
	             type="text"
	             size="small">
	             编辑
	           </el-button>
	           <el-button
	             @click="deleteRow(scope.row.employeeID)"
	             type="text"
	             size="small">
	             移除
	           </el-button>
	         </template>
	       </el-table-column>
	     </el-table>
		  <!-- 分页 -->
		<div class="block" style="text-align: center;">
  		<span class="demonstration"></span>
  		  <el-pagination
  		    @size-change="handleSizeChange"
  		    @current-change="handleCurrentChange"
  		    :current-page="pageIndex"
  		    :page-sizes="[8, 16, 24, 32]"
  		    :page-size="pageSize"
  		    layout="total, sizes, prev, pager, next, jumper"
  		    :total="totalItems" >
  		  </el-pagination>
  		</div>
	  
	    <!-- 编辑文本框 -->
		<el-dialog
      		title="编辑员工信息"
      		:visible.sync="dialogVisible2"
      		width="40%"
      		:before-close="handleClose2">
      		<el-form :label-position="labelPosition" label-width="80px" :model="rulesForm">

      		  <el-form-item label="姓名" prop="name">
      		    <el-input v-model="ruleForm.name"></el-input>
      		  </el-form-item>

				<el-form-item label="部门" prop="departmentID">
        		  <el-select v-model="ruleForm.departmentID" placeholder="请选择部门"  @change="handleDepartmentChange">
        		    <el-option
        		      v-for="department in departments"
        		      :key="department.departmentID"
        		      :label="department.departmentName"
        		      :value="department.departmentID">
        		    </el-option>
        		  </el-select>
        		</el-form-item>

				<el-form-item label="职位" prop="positionID">
        		  <el-select v-model="ruleForm.positionID" placeholder="请选择职位"  @change="handlePositionChange">
        		    <el-option
        		      v-for="position in positions"
        		      :key="position.positionID"
        		      :label="position.positionName"
        		      :value="position.positionID">
        		    </el-option>
        		  </el-select>
        		</el-form-item>

      		  <el-form-item label="入职日期" required>
      		    <el-col :span="11">
      		      <el-form-item prop="birthdate">
      		        <el-date-picker type="date" placeholder="选择日期" v-model="ruleForm.birthdate" style="width: 100%;"></el-date-picker>
      		      </el-form-item>
      		    </el-col>
      		    <el-col class="line" :span="2">-</el-col>
      		  </el-form-item>

      		  <el-form-item label="手机号" prop="phone">
      		    <el-input v-model="ruleForm.phone"></el-input>
      		  </el-form-item>

      		  <el-form-item label="邮箱" prop="email">
      		    <el-input v-model="ruleForm.email"></el-input>
      		  </el-form-item>

      		</el-form>
      		<span></span>
      		<span slot="footer" class="dialog-footer">
      		  <el-button type="primary" @click="editDataToTable">保存修改</el-button>
      		</span>
    	</el-dialog>

   </div>

</template>

<script>
	export default{
		name: '',
		components: {},

		mounted() {
			this.getDepartments();
			this.getPositions();
			this.list();
		},

		methods: {
			
			clearSearchQuery() {
    			this.searchQuery = '';
				this.list();
  			},

			handleChange(){
				if(this.searchQuery == "" || this.searchQuery == null){
					this.list();
				}else{
					this.pageIndex = 1; // 跳转到第一页
					this.handleSearch();
				}
			},

			handleClose2(){
				this.dialogVisible2 = false;
				this.list();
			},

			//修改数据打开对话框传入原来数据
			openDialog(row){
				this.dialogVisible2 = true;
                this.ruleForm = JSON.parse(JSON.stringify(row));
			},
			editDataToTable(){
				this.axios.post('/EmployeesModify', this.ruleForm)
       			.then(response => {
       		  	if (response.data.code === 200) {
       				this.$message.success(response.data.message);
       			} else {
       			  this.$message.warning(response.data.message);
       			}

       			// 关闭对话框并刷新列表
       			this.dialogVisible2 = false;
       			this.list();
       			})

       			.catch(error => {
       			  console.error(error);
       			  this.$message.error(error.response.data.message);
       			});
            },

			getDepartments() {
   			  this.axios.post('/DepartmentsList',{})
   			   .then(response => {
   			      this.departments = response.data.data.list;
				  console.log(this.departments);

   			    })
   			   .catch(error => {
   			      console.error(error);
   			    });
   			},
   			getPositions() {
   			  this.axios.post('/PositionsList',{})
   			   .then(response => {
   			      this.positions = response.data.data.list;
				  console.log(this.positions);
   			    })
   			   .catch(error => {
   			      console.error(error);
   			    });
   			},

			getDepartmentName(departmentID) {  
        		const department = this.departments.find(dep => dep.departmentID  === departmentID);  
        		return department ? department.departmentName : '未知部门';  
    		},  
    		getPositionName(positionID) {  
    		    const position = this.positions.find(pos => pos.positionID  === positionID);  
    		    return position ? position.positionName : '未知职位';  
    		},  

			handleDepartmentChange() {
      			// 当部门选择改变时，重新获取部门列表
    		  	this.getDepartments();
    		},
    		handlePositionChange() {
    		  	// 当职位选择改变时，重新获取职位列表
    		  	this.getPositions();
    		},

			handleSearch() {
				
				let params = {
				    name: this.searchQuery 
				};  
				
				this.axios.get("/EmployeesSearchByName",{params:params})
				.then(
					response=>{
						this.tableData=response.data.data;
						console.log(this.tableData)
						if (response.data.code === 200) {
							this.$message({
							  message: response.data.message,  
							  type: 'success'  
							});  
							
						}else{
							this.$message({
							  message: response.data.message,  
							  type: 'warning' 
							  });  
						}
					}
				)
				.catch(error => {
				        console.error(error);  
				        this.$message({  
				        message: error.response.data.message,  
				        type: 'error'  
				        });  
				    });  
			},
			
			deleteRow(id) {  
			    this.axios.get("EmployeesRemove",{
			        params: {
				employeeID: id
			        }
			      })
			    .then(
			    	response=>{
				this.list();
			    		console.log(response.data);
			    			this.$message.success('删除成功'); 
			    	}
			    )
			    .catch(error => {
			       console.error(error);
			     });
			  },
			
			//   分页相关
			handleCurrentChange(newPage) {
				console.log(`当前页: ${newPage}`);
  			  	this.pageIndex = newPage;
  			  	this.list(); // 重新加载数据
  			},
			handleSizeChange(newSize) {
  			  	console.log(`每页 ${newSize} 条`);
  			  	this.pageSize = newSize;
  			  	this.pageIndex = 1; // 当每页显示条数变化时，重置页码为1
  			  	this.list(); // 重新加载数据
  			},
			list() {
			     this.axios.post('EmployeesList', {
					pageIndex: this.pageIndex,
					pageSize: this.pageSize
				 })
			    .then(response => {
				this.tableData=response.data.data.list;
				this.totalItems = response.data.data.total; // 更新总记录数
				console.log(this.tableData);
			     })
			    .catch(error => {
			       console.error(error);
				     });
				},
		    },

		data(){
			return {

				labelPosition: 'right',
				dialogVisible2: false,
				pageIndex: '1',
				pageSize: '8',
				totalItems: '0',

				departments: [], // 用于存储部门数据
				positions: [], // 用于存储职位数据

				ruleForm: {
					name:'',
					birthdate: '',
					phone: '',
					email: '',
					departmentID: '',
					positionID: ''
				},

				rules: {
           			name: [
           			  { required: true, message: '请输入姓名', trigger: 'blur' }
           			],
           			birthdate: [
           			  { required: true, message: '请选择出生日期', trigger: 'change' }
           			],
           			phone: [
           			  { required: true, message: '请输入电话号码', trigger: 'blur' },
           			  { pattern: /^1[3456789]\d{9}$/, message: '电话号码格式不正确', trigger: 'blur' }
           			],
           			email: [
           			  { required: true, message: '请输入邮箱地址', trigger: 'blur' },
           			  { pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '邮箱地址格式不正确', trigger: 'blur' }
           			],
           			departmentID: [
           			  { required: true, message: '请选择部门', trigger: 'change' }
           			],
           			positionID: [
           			  { required: true, message: '请选择职位', trigger: 'change' }
           			]
          		},
			
			    searchQuery: '', 
			
			    tableData: [],   
			   
			    displayedData: [],
				items: [
        			{ id: 1, name: 'Item 1' },
        			{ id: 2, name: 'Item 2' }
      			]
		    }
		},

		 created() {  
		   this.displayedData = [...this.tableData];  
		},  
	
}
</script>

<style lang ="less" scoped>
		.pagination-center {
 		 	text-align: center;
		}

</style>